<?php

namespace App\Http\Controllers\Admin;


use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 图片直播黑名单用户
 */
class PictureLiveBlackController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\PictureLiveBlackUser();
        $this->validate = new  \App\Validate\PictureLiveBlackValidate();
    }

    /**
     * 黑名单用户列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        $res = $this->model->lists($keywords, $start_time, $end_time, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $res['data'] = $this->addSerialNumber($res['data']);
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }


    /** 
     * 黑名单用户新增   
     * @param user_id string 用户id 
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $is_exists = $this->model->nameIsExists($this->request->user_id, 'user_id', null, null);
        if ($is_exists) {
            return $this->returnApi(202, "该用户已存在");
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'user_id' => $this->request->user_id,
            ];
            $this->model->add($data);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id string 记录id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->where('id', $this->request->id)->delete();

        if ($res) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, '删除失败');
    }
}
